<?php
require 'vendor/autoload.php';
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\Style\{Alignment, Border, Fill};
use PhpOffice\PhpSpreadsheet\Worksheet\{PageSetup, Table};

require_once('./fun.php');


//var_dump($orders);

/**
 * 安全解析订单数据
 * @param array $order 原始订单数据
 * @return array 解析后的结构化数据
 */
function parseOrderData(array $order): array
{
    $proData = $order['order_pro'] ?? [];
    $items = [];

    foreach ($proData as $itemKey => $itemInfo) {
        $info = $itemInfo['info'] ?("(".$itemInfo['info'].")"):'';
        $items[] = [
            'id' => $itemInfo['id'],
            'name' =>   $itemInfo['title'].$info,
            'qty' => (int)$itemInfo['num'],
            'price' => (float)$itemInfo['total']
        ];
    }
    // 状态映射优化（新增状态显示）
    $statusMap = [
        1 => '待发货',
        5 => '已发货',
        10 => '完成',
        80 => '退款申请',
        99 => '售后'
    ];

    // 配送方式转换
    $yunMap = [
        'is_zt' => '门店自提',
        'is_ps' => '配送到家',
        'is_kd' => '快递'
    ];
    return [
        'order_id'    => (string)$order['id'],
        'user'        => (string)$order['name'],
        'phone'       => (string)$order['phone'],
        'pay_way'     => (string)$order['pay_way'],
        'total'       => (float)$order['pro_price'],
        'hd_id'       => (string)$order['hd_id'],
        'hd_title'    => base64($order['hd_title'] ?? ''),
        'yun'         => $yunMap[$order['yun']] ?? '未知配送方式',
        'items'       => $items,
        'order_time'  => gmdate('Y-m-d H:i:s', (int)$order['date']),
        'status'      => $statusMap[$order['state']] ?? '未知状态'
    ];
}

/**
 * 生成Excel文件
 * @param array $orders 解析后的订单数组
 */
function exportExcel($orders): void
{

    $orders = array_map('parseOrderData', $orders);
    $spreadsheet = new Spreadsheet();
    $sheet = $spreadsheet->getActiveSheet();
    $sheet->setTitle('订单数据');

    // 设置打印格式
    $sheet->getPageSetup()->setOrientation(PageSetup::ORIENTATION_LANDSCAPE);
    $sheet->getPageSetup()->setPaperSize(PageSetup::PAPERSIZE_A4);

    // 定义表头
    $headers = [
        '订单号', '联系人', '手机号', '支付方式', '订单金额',
        '活动ID', '活动名称', '配送方式', '订单状态', '下单时间',
        '商品ID', '商品名称', '数量', '单价', '小计'
    ];

    // 写入表头
    $sheet->fromArray([$headers], null, 'A1');

    // 设置标题样式
    $sheet->getStyle('A1:O1')->applyFromArray([
        'font' => ['bold' => true, 'color' => ['rgb' => 'FFFFFF']],
        'fill' => [
            'fillType' => Fill::FILL_SOLID,
            'startColor' => ['rgb' => '4F81BD']
        ],
        'alignment' => ['horizontal' => Alignment::HORIZONTAL_CENTER],
        'borders' => [
            'top'    => ['borderStyle' => Border::BORDER_THIN],
            'bottom' => ['borderStyle' => Border::BORDER_THIN]
        ]
    ]);

    // 填充数据
    $currentRow = 2;
    foreach ($orders as $order) {
        // 主订单信息
        $mainData = [
            $order['order_id'],
            $order['user'],
            $order['phone'],
            $order['pay_way'],
            $order['total'],
            $order['hd_id'],
            $order['hd_title'],
            $order['yun'],
            $order['status'],
            $order['order_time'],

        ];

        // 写入主数据
        $sheet->fromArray([$mainData], null, "A$currentRow");

        // 商品明细
        $itemRow = $currentRow;
        foreach ($order['items'] as $item) {
            $sheet->setCellValue("K$itemRow", $item['id'])
                ->setCellValue("L$itemRow", $item['name'])
                ->setCellValue("M$itemRow", $item['qty'])
                ->setCellValue("N$itemRow", $item['price'])
                ->setCellValue("O$itemRow", "=N$itemRow*M$itemRow");

            // 设置小计格式
            $sheet->getStyle("O$itemRow")->getNumberFormat()
                ->setFormatCode('#,##0.00');

            $itemRow++;
        }

        // 合并主订单单元格
        if ($itemRow - $currentRow > 1) {
            $sheet->mergeCells("A$currentRow:A" . ($itemRow - 1));
            $sheet->mergeCells("B$currentRow:B" . ($itemRow - 1));
            $sheet->mergeCells("C$currentRow:C" . ($itemRow - 1));
            $sheet->mergeCells("D$currentRow:D" . ($itemRow - 1));
            $sheet->mergeCells("E$currentRow:E" . ($itemRow - 1));
            $sheet->mergeCells("F$currentRow:F" . ($itemRow - 1));
            $sheet->mergeCells("G$currentRow:G" . ($itemRow - 1));
            $sheet->mergeCells("H$currentRow:H" . ($itemRow - 1));
            $sheet->mergeCells("I$currentRow:I" . ($itemRow - 1));
            $sheet->mergeCells("J$currentRow:J" . ($itemRow - 1));
        }

        $currentRow = $itemRow;
    }

    // 设置列宽
    $sheet->getColumnDimension('A')->setWidth(12);
    $sheet->getColumnDimension('B')->setWidth(15);
    $sheet->getColumnDimension('C')->setWidth(15);
    $sheet->getColumnDimension('D')->setWidth(10);
    $sheet->getColumnDimension('E')->setWidth(12);
    $sheet->getColumnDimension('F')->setWidth(10);
    $sheet->getColumnDimension('G')->setWidth(40);
    $sheet->getColumnDimension('H')->setWidth(10);
    $sheet->getColumnDimension('I')->setWidth(10);
    $sheet->getColumnDimension('J')->setWidth(20);
    $sheet->getColumnDimension('K')->setWidth(8);
    $sheet->getColumnDimension('L')->setWidth(25);
    $sheet->getColumnDimension('M')->setWidth(8);
    $sheet->getColumnDimension('N')->setWidth(10);
    $sheet->getColumnDimension('O')->setWidth(12);

    // 自动调整行高
    $sheet->getDefaultRowDimension()->setRowHeight(18);

//    // 添加表格格式
//    $table = new Table(1);
//    $sheet->addTable($table);
//    $tableStyle = [
//        'name' => 'TableStyleMedium9',
//        'showRowStripes' => true
//    ];
//    $table->setTableStyle($tableStyle);

    // 添加边框到所有单元格
    $sheet->getStyle('A1:O' . ($currentRow - 1))->applyFromArray([
        'borders' => [
            'allBorders' => ['borderStyle' => Border::BORDER_THIN]
        ]
    ]);

    // 生成响应
    $filename = '订单数据_' . date('YmdHis') . '.xlsx';
    header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
    header('Content-Disposition: attachment; filename="' . $filename . '"');
    header('Cache-Control: max-age=0');



    $writer = new Xlsx($spreadsheet);
    $writer->save('php://output');
    exit;
}

// 安全接收并验证JSON数据
$rawJson = file_get_contents('php://input');
$orders = json_decode($rawJson, true);

if (json_last_error() !== JSON_ERROR_NONE || !is_array($orders)) {
}else{
    // 执行导出
    exportExcel($orders);
}

